package com.naire.modul.dictionary.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.common.dao.GeneralDaoImpl;
import net.common.service.PageBean;
import net.common.util.BeanUtils;

import com.naire.modul.dictionary.dao.DictionaryDao;
import com.naire.modul.dictionary.pojo.Dictionary;
import com.naire.modul.dictionary.vo.DictionaryVo;
import com.naire.modul.dictype.pojo.Dictype;

public class DictionaryDaoImpl extends GeneralDaoImpl implements DictionaryDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<DictionaryVo> search(PageBean pageBean) throws Exception {
		StringBuilder hql = new StringBuilder("from Dictionary where flag=0");
		List<DictionaryVo> d = new ArrayList<DictionaryVo>();
		List<Dictionary> l = hibernateHandler.query(hql, pageBean);
		for(Dictionary bean : l) {
			DictionaryVo dv = new DictionaryVo();
			BeanUtils.copyProperties(bean, dv);
			d.add(dv);
		}
		return d;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer insert(DictionaryVo bean) throws Exception {
		Dictionary pojo = new Dictionary();
		BeanUtils.copyProperties(bean, pojo);
		String hql = "from Dictype where sort_num=:sort_num";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sort_num", bean.getSort_num());
		List<Dictype> l = hibernateHandler.executeQuery(hql, params);
		if(l != null && l.size() > 0) {
			pojo.setDictype(l.get(0));
		}
		hibernateHandler.insert(pojo);
		return pojo.getDict_id();
	}

	@Override
	public void update(DictionaryVo bean) throws Exception {
		Dictionary pojo = (Dictionary)hibernateHandler.find(Dictionary.class, bean.getDict_id());
		BeanUtils.copyProperties(bean, pojo);
		hibernateHandler.update(pojo);
		BeanUtils.copyProperties(pojo, bean);
	}

	@Override
	public void updateFlag(DictionaryVo bean) throws Exception {
		Dictionary pojo = (Dictionary)hibernateHandler.find(Dictionary.class, bean.getDict_id());
		BeanUtils.copyProperties(bean, pojo);
		hibernateHandler.update(pojo);
		bean.setDict_num(pojo.getDict_num());
	}

	@Override
	public DictionaryVo find(Integer id) throws Exception {
		Dictionary pojo = (Dictionary)hibernateHandler.find(Dictionary.class, id);
		DictionaryVo bean = new DictionaryVo();
		BeanUtils.copyProperties(pojo, bean);
		return bean;
	}
}
